<?php defined('SYSPATH') or die('No direct script access.');

class Model_Services_FamilyPatient extends Model implements Jqgrid_GridListener{
	
	public $id_patient;
	public $family_patient = NULL;
	
	public function __construct($id=false){
		$this->id_patient = $id;
	}	
	
	public function count($criteria = false){
		return ORM::factory("dao_familypatient")->where("patient_id","=",$this->id_patient)->count_all();
	}
	
	public function getList($criteria = false){
			
		if (!$criteria)	$family_patient_list = ORM::factory("dao_familypatient")->where("patient_id","=",$this->id_patient)->find_all()->as_array();
		else $family_patient_list = ORM::factory("dao_familypatient")->where("patient_id","=",$this->id_patient)->order_by($criteria->sidx,$criteria->sord)->limit($criteria->limit)->offset($criteria->calcOffset())->find_all()->as_array();
	
		$dataset = array();
		foreach ($family_patient_list as $family_patient){
			$dataset[$family_patient->id] = array(	$family_patient->family->family_name,
														$family_patient->background_cardiac,
														$family_patient->background_cholesterol,
														$family_patient->background_diabetic,
														$family_patient->background_hypertension,
														$family_patient->patient_id);
		}
				
		return $dataset;
	}
	
	public function getCondition($orderfield, $ordertype, $start,$limit){
		return ORM::factory("dao_familypatient")->where("patient_id","=",$this->id_patient)->order_by($orderfield,$ordertype)->limit($limit)->find_all()->as_array();
	}
	
	public function get($id){
		return ORM::factory("dao_familypatient")->find($id);
	}
	
	public function save($id, array $data){
				
		$this->family_patient = ($id) ? ORM::factory("dao_familypatient",$id) : ORM::factory("dao_familypatient");
		
		//hacer funcion para pasar de string a numeros (una funcion sanitize input)
		$this->family_patient->family_id = intval($data['family_id']);
		$this->family_patient->patient_id = ($id) ? intval($data['patient_id']) : $this->id_patient;
		$this->family_patient->background_cardiac = intval($data['background_cardiac']);
		$this->family_patient->background_cholesterol = intval($data['background_cholesterol']);
		$this->family_patient->background_diabetic = intval($data['background_diabetic']);
		$this->family_patient->background_hypertension = intval($data['background_hypertension']);
		
				
		$this->family_patient->save();
		return $this->family_patient->id;
	}

	
	public function delete($id){
		$this->pathology_patient = ORM::factory("dao_familypatient",$id);
		$this->pathology_patient->delete();
		return $id;
	}
	
	/**
	 * 
	 * return all family background by patient
	 * @param int $id
	 */
	public function getPatientFamily($id=false){
		return ORM::factory("dao_familypatient")->where("patient_id","=",(!$id)?$this->id_patient:$id)->find_all()->as_array();		
	}
	
}
?>

